#pragma once

#include <memory>
#include <boost/asio.hpp>
#include <boost/log/trivial.hpp>

namespace net_channel {
namespace server {

class TcpListener : public std::enable_shared_from_this<TcpListener> {
public:
    explicit TcpListener(boost::asio::io_context& io_context, uint16_t port)
        : io_context_(io_context)
        , acceptor_(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) {}

    void start() {
        BOOST_LOG_TRIVIAL(info) << "TCP listener started on port " << acceptor_.local_endpoint().port();
        do_accept();
    }

private:
    void do_accept() {
        auto socket = std::make_shared<boost::asio::ip::tcp::socket>(io_context_);
        acceptor_.async_accept(*socket,
            [this, socket](const boost::system::error_code& error) {
                if (!error) {
                    BOOST_LOG_TRIVIAL(info) << "New client connected from " 
                                            << socket->remote_endpoint().address().to_string()
                                            << ":" << socket->remote_endpoint().port();
                    // TODO: Handle new client connection
                } else {
                    BOOST_LOG_TRIVIAL(error) << "Accept failed: " << error.message();
                }
                do_accept();
            });
    }

    boost::asio::io_context& io_context_;
    boost::asio::ip::tcp::acceptor acceptor_;
};

} // namespace server
} // namespace net_channel